import grails.converters.*

class DeviceController {

    def authenticateService

    def index = {redirect(action: list, params: params)}

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def list = {
        if (!params.max) params.max = 10
        // if (!params.offset) params.offset = 0

        if (authenticateService.ifAllGranted('ROLE_ADMIN')) {
            def results = Device.list(params)
            return [deviceList: results]
        } else if (authenticateService.ifAllGranted('ROLE_USER')) {
            def domain = authenticateService.userDomain()
            def user = User.get(domain.id)
            def results = []
            //FIXME 
            user.groups?.each {
                devicegroup ->
                devicegroup.devices?.each {
                    device ->
                    results << device
                }
            }
            return [deviceList: results]
        } else {

        }

    }

    def report2KML = {
        if (!params.id) {
            flash.message = "Device id not provided"
            redirect(action: list)
        } else {
            def device = Device.get(params.id)
            if (!device) {
                flash.message = "Device not found with id ${params.id}"
                redirect(action: list)
            }
            else {
                render Eventdata.findAllByDevice(device) as KML
            }
        }
    }


    def report2XML = {
        println "report2XML"
        println params
        if (!params.id) {
            flash.message = "Device id not provided"
            redirect(action: list)
        } else {
            def device = Device.get(params.id)
            if (!device) {
                flash.message = "Device not found with id ${params.id}"
                redirect(action: list)
            }
            else {render Eventdata.findAllByDevice(device, [max: 500,
                    sort: "timestamp",
                    order: "desc"]) as XML}
        }
    }

    def trackAjax = {
        println "trackAjax"
        println params
        def device = Device.get(params.id)
        if (!device) {
            return
            //render "Device not found with id ${params.id}"
        }
        else {
            if (params.dt && params.df) {
                println "updating map"
                def from = new Date(Long.parseLong(params.df))
                def to = 	new Date(Long.parseLong(params.dt))
                
                //println from 
                //println to
                
                render Eventdata.findAllByDeviceAndTimestampBetween(device,from, to , [max: 100,
                        sort: "timestamp",
                        order: "desc"]) as JSON
            } else {
                println "default map"
                render Eventdata.findAllByDevice(device, [max: 100,
                        sort: "timestamp",
                        order: "desc"]) as JSON
            }
        }
    }


    def show = {
        def device = Device.get(params.id)
        def user = authenticateService.userDomain()

        if (!device) {
            flash.message = "Device not found with id ${params.id}"
            redirect(action: list)
        } else {
            if (authenticateService.ifAllGranted('ROLE_ADMIN')) {
                return [device: device]
            } else if (authenticateService.ifAllGranted('ROLE_USER')) {
                if (device.devicegroup.user.id == user.id) {
                    return [device: device]
                } else {
                    flash.message = "Device not found with id ${params.id}"
                    redirect(action: list)
                }
            } else {
            }
        }
    }

    def delete = {
        def device = Device.get(params.id)
        def user = authenticateService.userDomain()

        if (!device) {
            flash.message = "Device not found with id ${params.id}"
            redirect(action: list)
        } else {
            if (authenticateService.ifAllGranted('ROLE_ADMIN')) {
                device.delete()
                flash.message = "Device ${params.id} deleted"
                redirect(action: list)
            } else if (authenticateService.ifAllGranted('ROLE_USER')) {
                if (device.devicegroup.user.id == user.id) {
                    device.delete()
                    flash.message = "Device ${params.id} deleted"
                    redirect(action: list)
                } else {
                    flash.message = "Device not found with id ${params.id}"
                    redirect(action: list)
                }
            } else {
            }
        }
    }

    def edit = {
        def device = Device.get(params.id)

        if (!device) {
            flash.message = "Device not found with id ${params.id}"
            redirect(action: list)
        }
        else {
            if (authenticateService.ifAllGranted('ROLE_ADMIN')) {
                return [device: device]
            } else if (authenticateService.ifAllGranted('ROLE_USER')) {
                if (device.devicegroup.user.id == user.id) {
                    return [device: device]
                } else {
                    flash.message = "Device not found with id ${params.id}"
                    redirect(action: list)
                }
            } else {
            }

        }
    }

    def update = {
        def device = Device.get(params.id)
        if (device) {
            device.properties = params

            if (authenticateService.ifAllGranted('ROLE_ADMIN')) {
                if (!device.hasErrors() && device.save()) {
                    flash.message = "Device ${params.id} updated"
                    redirect(action: show, id: device.id)
                } else {
                    render(view: 'edit', model: [device: device])
                }
            } else if (authenticateService.ifAllGranted('ROLE_USER')) {
                if (params.devicegroup.id) {
                    def dg = devicegroup.get(params.devicegroup.id)
                    if (dg.user.id == authenticateService.userDomain().id) {
                        if (!device.hasErrors() && device.save()) {
                            flash.message = "Device ${params.id} updated"
                            redirect(action: show, id: device.id)
                        } else {
                            render(view: 'edit', model: [device: device])
                        }
                    } else {
                        render(view: 'edit', model: [device: device])
                    }
                } else {
                }
            }
        } else {
            flash.message = "Device not found with id ${params.id}"
            redirect(action: edit, id: params.id)
        }
    }

    def create = {
        def device = new Device()
        device.properties = params
        return ['device': device]
    }

    def save = {
        def device = new Device(params)
        if (!device.hasErrors() && device.save()) {
            flash.message = "Device ${device.id} created"
            redirect(action: show, id: device.id)
        }
        else {
            render(view: 'create', model: [device: device])
        }
    }
}